'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;

  require('./router/admin')(app);
  require('./router/api')(app);
  require('./router/chat')(app);

  app.ws.use(async (ctx, next) => {
    let user = null;

    const token = ctx.headers.authorization;

    if (!token) {
      ctx.websocket.send(JSON.stringify({
        msg: "deny",
        data: '错误的token'
      }));
      return ctx.websocket.close();
    }
    try {
      user = await ctx.checkToken(token);
      // 验证用户状态
      if (!user) {
        ctx.websocket.send(JSON.stringify({
            msg: "deny",
            data: '验证失败,请重新登录'
        }));
        return ctx.websocket.close();
      }
    } catch (e) {
      // 验证用户状态
      if (!user) {
        ctx.websocket.send(JSON.stringify({
            msg: "deny",
            data: '验证失败,请重新登录'
        }));
        return ctx.websocket.close();
      }
    }

    
    app.ws.user = app.ws.user ? app.ws.user : {};
    app.ws.user[user.userId] = ctx.websocket;

    ctx.online(user.userId)
    await next();
  });
  // websocket
  app.ws.route('/ws', controller.chat.connect);
  router.get('/u8jvZTpVbo.txt', controller.home.u8jvZTpVbo);
  
  router.get('login', '/login', controller.home.login);

  router.get('/', controller.home.index);

  router.get('/healthcheck', controller.check.healthCheck)

  router.get('dashboard','/dashboard', controller.home.dashboard);
  router.get('order-list','/order/list', controller.home.orderList);
  
  router.get('/user', controller.home.user);

  router.get('sub-order-list', '/sub-order/list', controller.home.subOrder);
  router.get('specialist-list', '/specialist/list', controller.home.specialist);
  router.get('customer-list', '/customer/list', controller.home.customerList);
  
  router.get('/user/login.json', controller.user.login);
  router.get('/wx/poster/:topicId', controller.home.posterWxView);
};
